from datetime import datetime
import random

class Util:
    @classmethod
    def toDateTime(cls, s):
        try:
            return datetime.strptime(s, "%m/%d/%Y %I:%M%p")
        except:
            return datetime.today()

    @classmethod
    def toDateTimeStr(cls, d):
        return d.strftime("%m/%d/%Y %I:%M%p")

    @classmethod
    def trim(cls, s):
        return s.strip().strip('._/\\%,!?&;"\'+=-~`(){}[]|#@$^*<>')

    @classmethod
    def toURL(cls, s):
        escape = {' ': '_', '\t': '_', '\n': '_', '\r': '_', '"': '', "'": '', '~': '',
            '`': '', '!': '', '@': '', '#': '', '$': '', '%': '', '^': '', '&': '',
            '*': '', '(': '', ')': '', '[': '', ']': '', '{': '', '}': '', '/': '',
            '\\': '', '?': '', '<': '', '>': ''
        }
        for e in escape:
            s = s.replace(e, escape[e])
        return cls.trim(s.lower())

    @classmethod
    def genkey(cls, l=10, x='0123456789abcdefghijklmnopqrstuvwxyz'):
        return ''.join([random.choice(x) for i in range(l)])

    @classmethod
    def getext(cls, filename):
        return filename.split('.')[-1]

    @classmethod
    def quote(cls, s):
        return '"%s"' % s.replace('"', '\\"')
        